package com.open.system.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.open.system.domain.LoanApplyDO;
import com.open.system.domain.LoanApplyLogDO;
import com.open.system.domain.RepayLogDO;
import com.open.system.service.LoanApplyLogService;
import com.open.system.service.LoanApplyService;
import com.open.system.service.LoanUserService;
import com.open.system.service.RepayLogService;
import com.open.common.utils.DateUtils;
import com.open.common.utils.PageUtils;
import com.open.common.utils.Query;
import com.open.common.utils.R;
import com.open.loan.utils.cal.AverageCapitalUtils;

/**
 * 
 * 
 * @author aaa
 * @email aaax
 * @date 2019-01-01 19:42:12
 */
 
@Controller
@RequestMapping("/system/repayLog")
public class RepayLogController {
	@Autowired
	private RepayLogService repayLogService;
	
	@Autowired
	private LoanApplyService loanApplyService;
	
	@Autowired
	private LoanUserService loanUserService;
	
	@Autowired
	private LoanApplyLogService loanApplyLogService;
	
	
	@GetMapping()
	@RequiresPermissions("system:repayLog:repayLog")
	String RepayLog(){
	    return "system/repayLog/repayLog";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("system:repayLog:repayLog")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
		List<RepayLogDO> repayAll=new ArrayList<RepayLogDO>();
		int totalAll=0;
		params.put("status","0");
		params.put("remark1",DateUtils.formatTwo(new Date()));
        Query query = new Query(params);
		List<RepayLogDO> repayLogList = repayLogService.list(query);
		int total = repayLogService.count(query);
		repayAll.addAll(repayLogList);
		totalAll=total;
		
		params.put("status","2");
        Query query2 = new Query(params);
		List<RepayLogDO> repayLogList2 = repayLogService.list(query2);
		int total2 = repayLogService.count(query2);
		repayAll.addAll(repayLogList2);
		totalAll=totalAll+total2;
		PageUtils pageUtils = new PageUtils(repayAll, totalAll);
		return pageUtils;
	}
	
	@ResponseBody
	@GetMapping("/listTest/{status}")
	public PageUtils listTest(@PathVariable(value="status") String status) throws Exception{
		
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("status",status);
		map.put("remark2","0");
		List<LoanApplyDO>loanApplys=loanApplyService.list(map);
		for (int i = 0; i <loanApplys.size(); i++) {
			SimpleDateFormat objSDF = new SimpleDateFormat("yyyy-MM-dd");
			LoanApplyDO loanApply=loanApplys.get(i);
			//月
	        int month =Integer.parseInt(loanApply.getLoanPeriod())/30;
	        //日
	        int day=DateUtils.daysBetween(objSDF.parse(loanApply.getRemark5()),DateUtils.get15Day());
	        //利率
	        String yearRateStr="0.01";
	        if(loanApply.getLoanRate().contains("%")){
	        	yearRateStr=loanApply.getLoanRate().replace("%","");
	        	double a =Double.parseDouble(yearRateStr);
	        	a=a/100;
	        	yearRateStr=String.valueOf(a);
	        }else {
	        	yearRateStr=loanApply.getLoanRate();
	        	double a =Double.parseDouble(yearRateStr);
	        	a=a/100;
	        	yearRateStr=String.valueOf(a);
			}
	        double yearRate =Double.parseDouble(yearRateStr); // 月利率
			
			//每天利息
			BigDecimal everyDayLiXi=new BigDecimal(0);
			everyDayLiXi=loanApply.getLoanAmount().multiply(new BigDecimal(yearRate));
			everyDayLiXi=everyDayLiXi.divide(new BigDecimal(30),2, BigDecimal.ROUND_DOWN);
			//每月本金
			BigDecimal everyDayBen=new BigDecimal(0);
			everyDayBen=loanApply.getLoanAmount().divide(new BigDecimal(month),2, BigDecimal.ROUND_DOWN);
			everyDayBen=everyDayBen.divide(new BigDecimal(30),2, BigDecimal.ROUND_DOWN);
			//每月还款金额
			BigDecimal needAmt=loanApply.getLoanAmount().add(new BigDecimal(loanApply.getRemark1()));
			needAmt=needAmt.divide(new BigDecimal(month),2, BigDecimal.ROUND_DOWN);
			BigDecimal needAmt11=new BigDecimal(0);
			for (int j = 1; j <=month; j++) {
				RepayLogDO repay=new RepayLogDO();
				if(j==1){
					BigDecimal needBen=everyDayBen.multiply(new BigDecimal(day));
					//BigDecimal needLixi=everyDayLiXi.multiply(new BigDecimal(day));
					BigDecimal needLixi=new BigDecimal(loanApply.getRemark1()).divide(new BigDecimal(loanApply.getLoanPeriod()),2, BigDecimal.ROUND_DOWN);
					needLixi=needLixi.multiply(new BigDecimal(day));
					needAmt11=needBen.add(needLixi).setScale(0,BigDecimal.ROUND_DOWN);
					repay.setAmt(needAmt11);
				}else if (j==month) {
					BigDecimal needAmt22=needAmt.multiply(new BigDecimal(2));
					needAmt22=needAmt22.subtract(needAmt11);
					repay.setAmt(needAmt22);
				}else {
					repay.setAmt(needAmt);
				}
				repay.setCreateTime(new Date());
				repay.setPeriod(Long.valueOf(j));
				try {
				//repay.setRepayTime(objSDF.parse(DateUtils.getDateData(i,new Date())));
				String time=DateUtils.getDateData(j,objSDF.parse(loanApply.getRemark5()));
				time=time.substring(0, 7);
				time=time+"-15 00:00:00";
				repay.setRepayTime(objSDF.parse(time));
				
				if(new Date().getTime()>repay.getRepayTime().getTime()){
					repay.setStatus("2");
				}else {
					repay.setStatus("0");
				}
				} catch (ParseException e) {
					e.printStackTrace();
				}
				repay.setUserId(loanApply.getUserId());
				repay.setUserName(loanApply.getRealName());
				repayLogService.save(repay);
			}
		}
		return null;
	}
	
	public static String getDateData(int a,Date date){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH, a);
		return formatDate(cal.getTime(), "yyyy-MM-dd");
	}
    
    
    public static String formatDate(Date date, String format) {
		if (date == null) {
			return null;
		}
		SimpleDateFormat objSDF = new SimpleDateFormat(format);
		String strOrderDate = objSDF.format(date);
		return strOrderDate;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("system:repayLog:add")
	String add(){
	    return "system/repayLog/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("system:repayLog:edit")
	String edit(@PathVariable("id") Long id,Model model){
		RepayLogDO repayLog = repayLogService.get(id);
		model.addAttribute("repayLog", repayLog);
	    return "system/repayLog/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("system:repayLog:add")
	public R save( RepayLogDO repayLog){
		if(repayLogService.save(repayLog)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	//@RequiresPermissions("system:repayLog:edit")
	public R update( RepayLogDO repayLog){
		repayLog=repayLogService.get(repayLog.getId());
		repayLog.setStatus("1");
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("userId", repayLog.getUserId());
		LoanApplyLogDO applyLogDO=loanApplyLogService.getLastNewData(map);
		if(applyLogDO==null){
			return R.error(201,"用户还未上传合同");
		}
		List<LoanApplyDO>loanApply=loanApplyService.list(map);
		if(loanApply!=null && loanApply.size()>0){
			LoanApplyDO applyDO=loanApply.get(0);
			BigDecimal repayAmt=repayLog.getAmt();
			BigDecimal amt=new BigDecimal(0);
			if(StringUtils.isNotEmpty(applyDO.getRemark2())){
				amt=new BigDecimal(applyDO.getRemark2());
			}
			repayAmt=repayAmt.add(amt);
			applyLogDO.setAlreadyRepaymentAmt(repayAmt);
			applyDO.setRemark2(String.valueOf(repayAmt));
			loanApplyService.update(applyDO);
			loanApplyLogService.update(applyLogDO);
		}
		
		repayLogService.update(repayLog);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("system:repayLog:remove")
	public R remove( Long id){
		if(repayLogService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("system:repayLog:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		for (int i = 0; i < ids.length; i++) {
			long id=ids[i];
			RepayLogDO repayLog=repayLogService.get(id);
			repayLog.setStatus("1");
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("userId", repayLog.getUserId());
			LoanApplyLogDO applyLogDO=loanApplyLogService.getLastNewData(map);
			List<LoanApplyDO>loanApply=loanApplyService.list(map);
			if(loanApply!=null && loanApply.size()>0){
				LoanApplyDO applyDO=loanApply.get(0);
				BigDecimal repayAmt=repayLog.getAmt();
				BigDecimal amt=new BigDecimal(0);
				if(StringUtils.isNotEmpty(applyDO.getRemark2())){
					amt=new BigDecimal(applyDO.getRemark2());
				}
				repayAmt=repayAmt.add(amt);
				applyLogDO.setAlreadyRepaymentAmt(repayAmt);
				applyDO.setRemark2(String.valueOf(repayAmt));
				loanApplyService.update(applyDO);
				loanApplyLogService.update(applyLogDO);
			}
			repayLogService.update(repayLog);
		}
		return R.ok();
	}
	
}
